package com.learning.job.schedule.quartz.base.simple;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.StdSchedulerFactory;

/**
 * ClassName: SimpleJobRunner
 * Description: 简单教程： https://www.w3cschool.cn/quartz_doc/quartz_doc-2put2clm.html
 * Date: 2018/12/18 10:56 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class SimpleJobRunner {
    public static void main(String[] args) throws SchedulerException {

        // 定义Job
        JobKey jobKey = JobKey.jobKey("", "");
        JobDetail jobDetail = JobBuilder.newJob(SimpleJob.class)
                .withIdentity(jobKey)
                .usingJobData("key", "value")
                .storeDurably() // Durability：如果一个job是非持久的，当没有活跃的trigger与之关联的时候，会被自动地从scheduler中删除。
                .requestRecovery() // 如果一个job是可恢复的，并且在其执行的时候，scheduler发生硬关闭（hard shutdown)，则当scheduler重新启动的时候，该job会被重新执行。
                .build();

        jobDetail.getJobDataMap().put("key2", "value2");


        // 定义调度规则，马上启动，每2秒运行一次，共运行100次
        TriggerKey triggerKey = TriggerKey.triggerKey("", "");
        SimpleScheduleBuilder scheduleBuilder = SimpleScheduleBuilder
                .simpleSchedule()
                .withIntervalInSeconds(2)
                .withRepeatCount(100)
                .withMisfireHandlingInstructionFireNow() // Misfire机制
                .withMisfireHandlingInstructionNextWithExistingCount() // Misfire机制
                ;

        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerKey)
                .startNow()
                .withSchedule(scheduleBuilder)
                .modifiedByCalendar("") // Calendar用于从trigger的调度计划中排除时间段。处理一些节假日排除
                .withPriority(Trigger.DEFAULT_PRIORITY) // 优先级
                .build();


        // 定义调度器
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        scheduler.scheduleJob(jobDetail, trigger);


    }
}
